package com.zhiwei.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhiwei.mapper.UserMapper;
import com.zhiwei.pojo.User;
import com.zhiwei.vo.PageResult;
import com.zhiwei.vo.UserInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Objects;
import java.util.UUID;

@Slf4j
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public List<User> getlist() {
        return userMapper.selectList(new QueryWrapper<User>().eq("isystem", 0));
    }

    @Override
    public UserInfo login(User user) {
        String pwd = user.getPassword() + "智为";
        pwd = DigestUtils.md5DigestAsHex(pwd.getBytes(StandardCharsets.UTF_8));
        User dbUser = findUser(user.getLoginName());
        if (Objects.isNull(dbUser)) {
            throw new RuntimeException("用户不存在");
        }
        if (!dbUser.getStatus()) {
            throw new RuntimeException("用户被禁用");
        }
        if (!dbUser.getPassword().equals(pwd)) {
            log.error("密码不匹配，用户端：{}，数据库端：{}", pwd, dbUser.getPassword());
            throw new RuntimeException("密码不匹配");
        }
        UserInfo userInfo = new UserInfo();
        String token = UUID.randomUUID().toString().replace("-", "");
        return userInfo.setUser(dbUser).setToken(token);
    }

    @Override
    public int addUser(User user) {
        String pwd = user.getPassword() + "智为";
        pwd = DigestUtils.md5DigestAsHex(pwd.getBytes());
        user.setPassword(pwd);
        return userMapper.insert(user);
    }

    @Override
    public User getUser(Integer userId) {
        return userMapper.selectById(userId);
    }

    @Override
    public User findUser(String name) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("login_name", name);
        return userMapper.selectOne(wrapper);
    }

    @Override
    public User getUserById(Integer id) {
        return userMapper.selectById(id);
    }

    @Override
    public int getMsgNum(Integer userId) {
        User user = userMapper.selectById(userId);
        return user.getMsgNum();
    }

    @Override
    public void updateUser(User user) {
        userMapper.updateById(user);
    }

    @Override
    public void resetPassword(User user) {
        String pwd = user.getPassword() + "智为";
        pwd = DigestUtils.md5DigestAsHex(pwd.getBytes());
        user.setPassword(pwd);
        userMapper.updateById(user);
    }


    /* 查询1
 sql:select * from user limit arg1,arg2
 查询第一页 每一页20条
 select * from user limit 0,20
 第二页
 select * from user limit 20,20
 第三页
 select * from user limit 40,20
 第n也
 select * from user limit (n-1)*20,20
 带条件的sql
 select * from user where name like "%#{query}%" limit (n-1)*20,20

 selectPage(1,2)     1:分页的对象  2.分页查询的条件
  */
    @Override
    public PageResult getUserList(PageResult pageResult) {

        //查询构造器
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        boolean flag = StringUtils.hasLength(pageResult.getQuery());
        //动态sql flag为真时 才拼接where条件
        queryWrapper.like(flag, "username", pageResult.getQuery())
                .eq("isystem", false);

        //定义分页对象
        IPage<User> page = new Page<>(pageResult.getPageNum(), pageResult.getPageSize());

        //MP提供的分页对象  包含了分页的数据结果信息
        page = userMapper.selectPage(page, queryWrapper);

        return pageResult.setRows(page.getRecords()).setTotal(page.getTotal());
    }

    @Override
    public void updateStatus(User user) {
        userMapper.updateById(user);
    }

    @Override
    public void addMyUser(User user) {
        String pwd = user.getPassword() + "智为";
        pwd = DigestUtils.md5DigestAsHex(pwd.getBytes());
        user.setPassword(pwd)
                .setMsgNum(0)
                .setLeaderId(7)
                .setIsmanager(4)
                .setIsystem(false)
                .setStatus(false);
        userMapper.insert(user);
    }

    @Override
    public void deleteUser(Integer id) {
        User user = userMapper.selectById(id);
        user.setStatus(false);
        userMapper.updateById(user);
    }

    @Override
    public User selectById(Integer userId) {
        return userMapper.selectById(userId);
    }

    @Override
    public int updateById(User user) {
        return userMapper.updateById(user);
    }
}
